package x2rel.qMap.core;

import x2rel.qMap.logger.Logging;

//Java
import java.io.File;
import java.util.ArrayList;

//SAXON
public class EquivalenciaHandler extends XmlHandler {

    private File xmlfile;
    private ArrayList<Variables> vars;

    public EquivalenciaHandler(File equivFile, ArrayList<Variables> vars) {

        this.xmlfile = equivFile;
        this.vars = vars;

    }

    public ArrayList<Equivalencias> executa() {

        ArrayList<Equivalencias> eqs = new ArrayList<Equivalencias>();

        for (Variables v : vars) {
            String s = getEquivalencias(v);
            //Logging.getInstance().log("Saida!\n" + s);
            eqs.add(new Equivalencias(v.getName(), s, v.getCod()));
        }

        return eqs;

    }

    private String getEquivalencias(Variables v) {
        //the xquery string
        String xq;
        //String xpath = "/catalog/book/genre";
        String xpath = v.getXpath();
        String sourceid = v.getDocument();
        String saida = "";

        xq = "  xquery version \"1.0\";"
                + " for $c in //concept,"
                + " $s in $c/source"
                + " where $s/@id=\"" + sourceid + "\" and $s/xpath=\"" + xpath + "\""
                + " return "
                + "   <relational>"
                + "     <column>{$c/relational/name/text()}</column>"
                + "     <table>{$c/relational/table/text()}</table>"
                + "     <domain>{$c/relational/domain/text()}</domain>"
                + "     <type>{$c/relational/type/text()}</type>"
                + "     <name>{$c/relational/name/text()}</name>"
                + "   </relational>";

        try {
            saida = runXquery(this.xmlfile, xq);
        }catch (Exception e) {
            Logging.getInstance().log("Ocorreu um erro ao buscar no documento de mapeamento. Detalhes: " + e);
            System.exit(1);
        } finally {
            return saida;
        }

    }
    /*
    try {
    
    Logging.getInstance().log("Processamento do documento de mapeamento de equivalências iniciado. (" + equivFile.getName() + ")");
    
    
    //            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //            DocumentBuilder db = dbf.newDocumentBuilder();
    //            Document doc = (Document) db.parse(equivFile);            
    //            
    //            Element root = doc.getDocumentElement();
    //            
    //            NodeList elements = root.getChildNodes();
    //            
    //            for(int i = elements.getLength() - 1; i >= 0; i--){
    //            
    //            }
    //            
    //the Q.xquery file
    File XMLStream = equivFile;
    
    String xquery = "xquery version \"1.0\";"
    + " for $c in //concept, $s in $c/source"
    + " where $s/@id=\"DocumentoA_v2.xml\" "
    + " and $s/xpath=\"/banco/conta/saldo\" "
    + " return <relational>"
    + " <column>{$c/relational/name/text()}</column> "
    + " <table>{$c/relational/table/text()}</table> "
    + " <domain>{$c/relational/domain/text()}</domain> "
    + " </relational> ";
    
    Logging.getInstance().log(xquery, 1);
    //print the result to the console
    OutputStream destStream = System.out;
    
    //compile the XQuery expression
    XQueryExpression exp = null;
    
    //create a Configuration object
    Configuration C = new Configuration();
    
    //static and dynamic context
    StaticQueryContext SQC = new StaticQueryContext(C);
    DynamicQueryContext DQC = new DynamicQueryContext(C);
    
    //indentation
    Properties props = new Properties();
    props.setProperty(OutputKeys.METHOD, "xml");
    props.setProperty(OutputKeys.INDENT, "yes");
    
    try {
    //queryStream= new FileInputStream(queryFileName);
    //FileInputStream queryStream= new FileInputStream(queryFileName);
    
    SQC.setBaseURI(equivFile.toURI().toString());
    
    //compilation
    exp = SQC.compileQuery(xquery);
    //SQC=exp.getStaticContext(); 
    } catch (net.sf.saxon.trans.XPathException e) {
    System.err.println(e.getMessage());
    }
    
    //get the XML ready
    try {
    InputSource XMLSource = new InputSource(XMLStream.toURI().toString());
    SAXSource SAXs = new SAXSource(XMLSource);
    DocumentInfo DI = SQC.buildDocument(SAXs);
    DQC.setContextNode(DI);
    
    //evaluating
    exp.run(DQC, new StreamResult(destStream), props);
    destStream.close();
    } catch (net.sf.saxon.trans.XPathException e) {
    System.err.println(e.getMessage());
    } catch (java.io.IOException e) {
    System.err.println(e.getMessage());
    }
    
    
    
    
    
    //            
    //            } catch (ParserConfigurationException ex) {
    //            Logging.getInstance().log("O parser não foi configurado corretamente.\nDetalhes: "+ex.getMessage(),3);
    //            } catch (SAXException ex) {
    //            Logging.getInstance().log("Ocorreu um erro ao fazer o parse do arquivo.\nDetalhes: "+ex.getMessage(),3);
    //            } catch (IOException ex) {
    //            Logging.getInstance().log("Ocorreu um erro ler o arquivo.\nDetalhes: "+ex.getMessage(),3);
    //            }
    } catch (Exception ex) {
    Logging.getInstance().log("Ocorreu um erro.\nDetalhes: " + ex.getMessage(), 3);
    }
     */
    /*
    
    private String runXqIntoEquivFile(Variables v) {
    //the xquery string
    String xq;
    //String xpath = "/catalog/book/genre";
    String xpath = v.getXpath();
    String sourceid = v.getDocument();
    String saida = "";
    
    xq = "  xquery version \"1.0\";"
    + " for $c in //concept,"
    + " $s in $c/source"
    + " where $s/@id=\"" + sourceid + "\" and $s/xpath=\"" + xpath + "\""
    + " return "
    + "   <relational>"
    + "     <column>{$c/relational/name/text()}</column>"
    + "     <table>{$c/relational/table/text()}</table>"
    + "     <domain>{$c/relational/domain/text()}</domain>"
    + "   </relational>";
    
    return runXquery(this.xmlfile, xq);
    //return Utils.runXquery(this.xmlfile, xq);
    
    /*
    Logging.getInstance().log("XQuery executada: <br />" + xq);
    
    // Xml file
    File XMLStream = this.xmlfile;
    
    //compile the XQuery expression
    XQueryExpression exp = null;
    
    //create a Configuration object
    Configuration C = new Configuration();
    
    //static and dynamic context
    StaticQueryContext SQC = new StaticQueryContext(C);
    DynamicQueryContext DQC = new DynamicQueryContext(C);
    
    //indentation
    Properties props = new Properties();
    props.setProperty(OutputKeys.METHOD, "xml");
    props.setProperty(OutputKeys.INDENT, "yes");
    
    try {
    
    //compilation
    exp = SQC.compileQuery(xq);
    //SQC = exp.getStaticContext();
    } catch (net.sf.saxon.trans.XPathException e) {
    System.err.println(e.getMessage());
    }
    //        catch (java.io.IOException e) {
    //            System.err.println(e.getMessage());
    //        }
    
    //get the XML ready
    try {
    
    //XMLStream = new File(xmlFileName);
    InputSource XMLSource = new InputSource(XMLStream.toURI().toString());
    SAXSource SAXs = new SAXSource(XMLSource);
    DocumentInfo DI = SQC.buildDocument(SAXs);
    DQC.setContextNode(DI);
    
    //evaluating
    //            exp.run(DQC, new StreamResult(destStream), props);
    //            destStream.close();
    
    
    //saida em string
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StreamResult result = new StreamResult(new StringWriter());
    exp.run(DQC, result, props);
    //DOMSource source = new DOMSource(new Doc);
    //transformer.transform(source, result);
    saida = result.getWriter().toString();
    
    
    
    } catch (net.sf.saxon.trans.XPathException e) {
    System.err.println(e.getMessage());
    } catch (TransformerConfigurationException e) {
    System.err.println(e.getMessage());
    } catch (TransformerException e) {
    System.err.println(e.getMessage());
    }
    
    return saida;
    
    }
    
     */
}
